package cn.aitrox.ry.common.interceptor;

import cn.aitrox.ry.common.service.api.dto.User;
import cn.aitrox.ry.util.JSONUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
public class UserInterceptor extends HandlerInterceptorAdapter {

    private static final String USER = "User";

    @Autowired
    private UserThreadLocal userThreadLocal;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userStr = request.getHeader(USER);
        if(StringUtils.isEmpty(userStr)) {
            return false;
        }

        User user = JSONUtil.fromJson(userStr, User.class);

        userThreadLocal.setUser(user);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                @Nullable Exception ex) throws Exception {
        userThreadLocal.clear();
    }
}
